package br.pucrs.lognplay.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.pucrs.lognplay.entity.User;
import br.pucrs.lognplay.entity.User.Role;

public class SecurityFilter implements Filter {

	public static final String LOGGED_USER_ATTRIBUTE = "LOGGED_USER";

	private static final String PROTECTED_DIRECTORY = "/protected";

	private static final String MASTER_USER_DIRECTORY = PROTECTED_DIRECTORY + "/master";

	private static final String CLIENT_MASTER_USER_DIRECTORY = PROTECTED_DIRECTORY + "/clientMaster";

	private static final String CLIENT_USER_DIRECTORY = PROTECTED_DIRECTORY + "/client";

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

		String contextPath = httpServletRequest.getContextPath();
		String requestURI = httpServletRequest.getRequestURI();

		Boolean secure = false;

		if (requestURI.startsWith(contextPath + PROTECTED_DIRECTORY)) {
			HttpSession httpSession = httpServletRequest.getSession();
			User loggedUser = (User) httpSession.getAttribute(LOGGED_USER_ATTRIBUTE);

			if (loggedUser != null) {
				Role loggedUserRole = loggedUser.getRole();

				if (requestURI.startsWith(contextPath + MASTER_USER_DIRECTORY)) {
					if (loggedUserRole.equals(Role.MASTER_USER)) {
						secure = true;
					}
				} else if (requestURI.startsWith(contextPath + CLIENT_MASTER_USER_DIRECTORY)) {
					if (loggedUserRole.equals(Role.MASTER_USER) || loggedUserRole.equals(Role.CLIENT_MASTER_USER)) {
						secure = true;
					}
				} else if (requestURI.startsWith(contextPath + CLIENT_USER_DIRECTORY)) {
					if (loggedUserRole.equals(Role.MASTER_USER) || loggedUserRole.equals(Role.CLIENT_MASTER_USER) || loggedUserRole.equals(Role.CLIENT_USER)) {
						secure = true;
					}
				}
			}
		} else {
			secure = true;
		}

		if (secure) {
			filterChain.doFilter(servletRequest, servletResponse);
		} else {
			httpServletResponse.sendRedirect(contextPath);
		}
	}

	public void destroy() {

	}
}
